#include "Texture.h"
#include "string.h"
#include "Logger.h"
#include <stdio.h>
#include <stdlib.h>

TextureDB textureDB;

TextureDB::TextureDB(){
    totalTextures=0;
    t=0;
}
Img* TextureDB::make(const char *filename){
    if (!filename){errLog.print("Trying to load a texture with no name");return 0;}
    if (!fileExists(filename)){errLog.print(Str()<<"TextureDB -> The file \""<<filename<<"\" cannot be opened");return 0;}
    /*Str ext;
    ext = filename;
    ext.fixEdgeFormating(" \t\n");
    ext.keep(ext.rfind(".")+1,0);
    ext.toLower();*/
    
    totalTextures++;
    resize();
    
	bool success=false;
    /*if (ext=="bmp")
	{
		success = t[totalTextures-1].loadBmp(filename);
	}
    else if (ext=="jpg"||ext=="jpeg")
	{
		success = t[totalTextures-1].loadJpg(filename);
	}
    else if (ext=="png")
	{
		success = t[totalTextures-1].loadPng(filename);
	}*/
	success = t[totalTextures-1].load(filename);
	//if it did not succeed, we still cannot use that space
    if (success)
	{
		errLog.print(Str()<<"TextureDB::make(\""<<filename<<"\") -> succeeded");
		return &t[totalTextures-1];
	}
    totalTextures--;
    resize();
    errLog.print(Str()<<"TextureDB::make(\""<<filename<<"\") -> Did not succeed");
    return 0;
}
TextureDB::~TextureDB(){if (t!=0){free(t);}}
void TextureDB::resize(){
    if (t==0){t=(Img*)malloc(totalTextures*sizeof(Img));}
    else if (totalTextures==0){free(t);t=0;}
    else{t=(Img*)realloc(t,totalTextures*sizeof(Img));}
}
bool TextureDB::fileExists(const char *filename){
    bool doesit;
    FILE * file;
    file = fopen(filename,"r");
    doesit = !file?false:true;
    fclose(file);
    return doesit;
}
void TextureDB::use(int textureIndex){
    t[textureIndex].use();
}
